package com.sts.common.utils;

import com.sts.config.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

@Component
public class JwtUtil {
    private final SecretKey secretKey;
    private final long expirationMillis;

    @Autowired
    public JwtUtil(JwtProperties jwtProperties) {
        // 将Base64密钥转换为SecretKey
        this.secretKey = Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes());
        this.expirationMillis = jwtProperties.getExpiration() * 1000;
    }
    // 生成令牌
    public String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + expirationMillis))
                .signWith(secretKey, SignatureAlgorithm.HS256)
                .compact();
    }

    // 解析令牌
    public Map<String, Object> parseToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(token)
                .getBody();
        return claims;
    }
    //计算指定 Token 距离过期还剩余多少秒
    public long getRemainingSeconds(String token) {
        Claims claims = (Claims) parseToken(token);
        long exp = claims.getExpiration().getTime();
        long now = System.currentTimeMillis();
        return Math.max(0, (exp - now) / 1000);
    }
    //添加一个方法来获取Token的过期时间：
    public Date getExpirationDate(String token) {
        Claims claims = (Claims) parseToken(token);
        return claims.getExpiration();
    }
}